package net.vinote.smart.platform.service.dw.html;

import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import net.vinote.smart.platform.service.SRE;
import net.vinote.smart.platform.service.bean.CodeLibrary;

public class SelectTag extends HtmlTag {
	// private String htmlTemplate =
	// "<select #attributes value='#value'>#option</select>";
	private String htmlTemplate = "<select #attributes >#option</select>";

	public SelectTag(HtmlTag htmlTag) {
		super(htmlTag);
	}

	@Override
	public String getHtmlTemplate() {
		return htmlTemplate;
	}

	protected void initPlaceHolder() {
		String htmlSource = getHtmlSource();
		if ("Code".equals(htmlSource)) {
			placeholder.put("#option", getOptionByCode());
		} else if ("JsonArray".equals(htmlSource)) {
			placeholder.put("#option", getOptionByJsonArray());
		} else if (htmlSource == null || "".equals(htmlSource.trim())) {
		}
		placeholder.put("#value", getValue());
	}

	private String getOptionByCode() {
		StringBuffer sb = new StringBuffer();
		if (!isRequired()) {
			sb.append("<option value=''/>");
		}
		Map<String, CodeLibrary> codeItemMap = SRE.getCodeItems(getHtmlVal());
		for (String itemNo : codeItemMap.keySet()) {
			sb.append("<option value='").append(itemNo).append("'");
			if (itemNo.equals(getValue())) {
				sb.append(" selected");
			}
			sb.append(">").append(codeItemMap.get(itemNo).getItemName())
					.append("</option>");
		}
		return sb.toString();
	}

	private String getOptionByJsonArray() {
		StringBuffer sb = new StringBuffer();
		if (!isRequired()) {
			sb.append("<option value=''/>");
		}
		CodeLibrary codeItem = SRE.getCodeItems("JsonArrayCode").get(
				getHtmlVal());
		JSONArray array = new JSONArray(codeItem.getAttr01());
		for (int i = 0; i < array.length(); i++) {
			JSONObject obj = array.getJSONObject(i);
			String code = obj.getString("code");
			String title = obj.getString("title");
			sb.append("<option value='").append(code).append("'");
			if (code.equals(getValue())) {
				sb.append(" selected");
			}
			sb.append(">").append(title).append("</option>");
		}
		return sb.toString();
	}
}
